# -*- coding: utf-8 -*-
import asyncio
import websocket
# import time

from src.sshconn.ssh_conn import SSHConn
# from apscheduler.schedulers.background import BackgroundScheduler
# from multiprocessing.dummy import Pool as ThreadPool
from lib.ucloud.logger import logger


service_env = dict(
    # c1=[
    #     "c1_dev",
    #     "c1_test",
    #     "c1_pre_release",
    #     "c1_release"
    # ],
    c2=[
        # "c2_dev",
        "c2_test",
        # "c2_pre_release",
        # "c2_release"
    ]
)


def on_message(ws, message):
    pass


def on_error(ws, error):
    ws.close()
    pass


def on_close(ws):
    ws.close()
    pass


def on_open(ws):
    SSHConn().read_log(ws, send_log)


def send_log(ws, msg):
    # logger.info(msg)
    ws.send(msg)


class WebSocketClient(object):
    def __init__(self, service_name):
        # websocket.enableTrace(True)
        self.ws = websocket.WebSocketApp('ws://0.0.0.0:5678/echo_ws?service_env=' + service_name,
                                         on_message=on_message,
                                         on_error=on_error,
                                         on_close=on_close)
        self.ws.on_open = on_open
        self.ws.run_forever(ping_interval=60, ping_timeout=5)


def run_admin_client():
    # pool = ThreadPool(10)
    list_server = []
    for (key, value) in service_env.items():
        for item in value:
            list_server.append(item)
    # pool.map(new_ws_client, list_server)
    tasks = []
    for child in list_server:
        # new_ws_client(child)
        tasks.append(asyncio.ensure_future(new_ws_client(child)))
    return tasks


def new_ws_client(name):
    WebSocketClient(name)


if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    tasks = run_admin_client()
    loop.run_until_complete(asyncio.wait(tasks))
    loop.close()
